import { LocalDataManager } from './storage/local-storage.js'

/**
 * 重定向到登录页
 * @message 非必填 跳转成功后提示信息
 */
export function redirectLoginPage(message: string): void {
  const pages = getCurrentPages()
  const loginPageUrl = 'pages/login/index'
  uni.$u.route({
    type: pages.length > 1 ? 'redirectTo' : 'reLaunch',
    url: loginPageUrl,
    params: {
      message,
      redirectPathUrl: pages[pages.length - 1].route
    }
  })
}

/**
 * 下载文件
 * @fileUrl 必填 文件资源路径
 */
export function downloadFile(fileUrl: string, cb?: Function): Promise<string> {
  return new Promise(async (resolve, reject) => {
    const downloadTask = uni.downloadFile({
      url: fileUrl,
      success: async (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath)
        } else {
          reject('下载失败')
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
    cb && cb(downloadTask)
  })
}

/**
 * 保存文件到设备
 */
export function saveFileToDevice(tempFilePath: string): Promise<string> {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    uni.saveFile({
      tempFilePath,
      success: res => {
        resolve(res.savedFilePath)
      },
      fail: err => {
        reject(err)
      }
    })
  })
  // #endif
}

/**
 * 获取设备上已保存的文件列表
 */
export function getSaveFileOnTheDevice(): Promise<UniApp.GetSavedFileListSuccessFileItem[]> {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    uni.getSavedFileList({
      success: res => {
        resolve(res.fileList)
      },
      fail: err => {
        reject(err)
      }
    })
  })
  // #endif
}


/**
 * 获取设备上保存的文件信息
 */
export function getSaveFileInfoOnTheDevice(filePath: string): Promise<boolean> {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    uni.getSavedFileInfo({
      filePath,
      success: res => {
        console.log(res)
        resolve(true)
      },
      fail: err => {
        console.log(err)
        resolve(false)
      }
    })
  })
  // #endif
}

/**
 * 删除设备上保存的文件
 */
export function removeSaveFileOnTheDevice(filePath: string): Promise<void> {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    uni.removeSavedFile({
      filePath,
      success: () => {
        resolve()
      },
      fail: () => {
        reject()
      }
    })
  })
  // #endif
}